using System.Collections.Generic;
using UnityEngine;

public class SpriteFrameAnim : MonoBehaviour
{
    [Header("渲染目标")]
    public SpriteRenderer targetImage;

    [Header("动画数据列表")]
    public List<SpriteAnimData> animClips;

    [Header("控制参数")]
    public float speedRate = 1f;
    public bool autoPlayOnAwake = true;
    public string defaultAnimKey = "idle";

    private Dictionary<string, SpriteAnimData> _clipDict = new();
    private string _currentAnimKey;
    private Sprite[] _spriteArray;
    private int _frameIndex;
    private float _timer;
    private bool _isLoop;
    private bool _isPlaying;

    private List<int> _frameList = new();
    private int _totalFrame;

    private void Awake()
    {
        // 初始化动画字典
        foreach (var clip in animClips)
        {
            if (!string.IsNullOrEmpty(clip.animKey))
                _clipDict[clip.animKey] = clip;
        }

        // 自动播放默认动画
        if (autoPlayOnAwake)
        {
            Play(defaultAnimKey);
        }
    }

    public void Play(string animKey, bool loop = true, bool force = false)
    {
        if (!force && _isPlaying && animKey == _currentAnimKey)
            return;

        // 获取动画配置
        if (!_clipDict.TryGetValue(animKey, out var clip))
        {
            Debug.LogWarning($"动画未找到：{animKey}");
            return;
        }

        // 设置循环和播放状态
        _isLoop = loop;
        _currentAnimKey = animKey;
        _frameIndex = 0;
        _timer = 0f;

        // 计算帧数据
        var frameMaxCount = Mathf.FloorToInt(clip.frameCount * clip.frameDuration * speedRate / 0.0333f);
        _totalFrame = frameMaxCount;

        _frameList = GenerateFrameSequence(clip.frameCount, _totalFrame);

        // 使用 GameCoreAssetManager 加载精灵资源
        GameCoreAssetManager.Instance.LoadSprite(clip.spriteName, clip.frameCount, () =>
        {
            _spriteArray = GameCoreAssetManager.Instance.GetSprites(clip.spriteName);
            if (_spriteArray != null && _spriteArray.Length > 0)
            {
                targetImage.sprite = _spriteArray[0];
                _isPlaying = true;
            }
        });
    }

    private void Update()
    {
        if (!_isPlaying || _spriteArray == null || _spriteArray.Length == 0)
            return;

        _timer += Time.deltaTime;
        var clip = _clipDict[_currentAnimKey];

        if (_timer >= clip.frameDuration / speedRate)
        {
            _timer = 0f;
            _frameIndex++;

            if (_frameIndex >= _totalFrame)
            {
                if (_isLoop)
                {
                    _frameIndex = 0; // 循环播放
                }
                else
                {
                    _isPlaying = false;
                    _frameIndex = _totalFrame - 1;
                }
            }

            // 更新精灵帧
            if (_frameIndex < _frameList.Count)
            {
                var frame = _frameList[_frameIndex];
                if (frame < _spriteArray.Length && _spriteArray[frame] != null)
                {
                    targetImage.sprite = _spriteArray[frame];
                }
            }
        }
    }

    private List<int> GenerateFrameSequence(int originalCount, int targetCount)
    {
        var result = new List<int>();
        if (originalCount == targetCount)
        {
            for (int i = 0; i < targetCount; i++) result.Add(i);
        }
        else if (originalCount > targetCount)
        {
            // 减帧：根据目标帧数精确选帧
            float interval = originalCount / (float)targetCount;
            for (int i = 0; i < targetCount; i++)
            {
                result.Add(Mathf.FloorToInt(i * interval));
            }
        }
        else
        {
            // 补帧：循环补充帧
            float interval = targetCount / (float)originalCount;
            for (int i = 0; i < targetCount; i++)
            {
                result.Add(i % originalCount);
            }
        }
        return result;
    }

    public void Stop() => _isPlaying = false;

    public string GetCurrentAnimKey() => _currentAnimKey;
}
